<?php


namespace app\community\controller;


use app\common\controller\Together;
use app\common\controller\Common;
use app\index\controller\Base;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class District extends Base
{

    //景区管理员视图
    public function index()
    {
        $where = "1=1";
        $status = $propertyName = $mobile = $name = '';
        $Together = new Together();
        $agent_city = $Together->ColonyCity();
        if (!empty($agent_city)) {
            $where .= " and c.cityRegionId in ($agent_city)";
        }
        if (!empty($_GET['status'])) {
            $where .= " and b.status =" . $_GET['status'];
            $status = $_GET['status'];
        }
        if (!empty($_GET['propertyName'])) {
            $where .= " and c.name like '%" . $_GET['propertyName'] . "%'";
            $propertyName = $_GET['propertyName'];
        }
        if (!empty($_GET['mobile'])) {
            $where .= " and d.mobile like '%" . $_GET['mobile'] . "%'";
            $mobile = $_GET['mobile'];
        }
        if (!empty($_GET['name'])) {
            $where .= " and b.name like '%" . $_GET['name'] . "%'";
            $name = $_GET['name'];
        }

        $thisWechat = Session::get("thisWechat");
        $where .= " and b.uniacid =" . $thisWechat['id'];


        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_colony_manager_colony")->alias("a")
                    ->join("community_colony_manager b", "a.manager_id = b.id")
                    ->join("community_colony c", "a.colony_id = c.id")
                    ->join("admin_fans d", "b.fans_id = d.id")
                    ->field("b.fans_id,d.mobile,b.id,d.realName,d.nickname,d.faceUrl,d.addtime,count('a.id') as count,b.status,b.name")
                    ->where($where)->limit($start, $limit)
                    ->group('b.id')->select();
                $count = Db::name("community_colony_manager_colony")->alias("a")
                    ->join("community_colony_manager b", "a.manager_id = b.id")
                    ->join("community_colony c", "a.colony_id = c.id")
                    ->join("admin_fans d", "b.fans_id = d.id")
                    ->where($where)
                    ->count("*");
                $enable_status = Db::name("config_attribute")->where(['key' => "enable_status"])->value("value");
                $enable_status = explode("|", $enable_status);
                foreach ($enable_status as $k => $v) {
                    $enable_status[$k + 1] = $v;
                }
                unset($enable_status[0]);
                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                    $list[$k]['status_name'] = $enable_status[$v['status']];
                    $v['faceUrl'] = empty($v['faceUrl']) ? "/static/images/nopic-107.png" : $v['faceUrl'];
                    $list[$k]['faceUrl'] = "<img src='".$v['faceUrl']."' style='height:50px'>";

                    $list[$k]['mobile'] = substr($v['mobile'], 0, 3) . '****' . substr($v['mobile'], 7, strlen($v['mobile']));
                    //拼接管理的小区信息
                    $community = Db::name("community_colony_manager_colony")->where(['manager_id' => $v['id']])->field("colony_id")->select();
                    $communityIds = array_column($community, "colony_id");
                    $community = Db::name("community_colony")->where(['id' => ['in', $communityIds]])->field("id,name")->select();
                    $community = array_column($community, "name");
                    $community = implode($community, ",");
                    $list[$k]['communityLists'] = $community;
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }


        $assign = [
            "status" => $status,
            "propertyName" => $propertyName,
            "mobile" => $mobile,
            "name" => $name
        ];
        $this->assign($assign);
        return $this->fetch('index');
    }

    //添加景区管理员视图
    public function addManager()
    {
        $where = [];
        $Together = new Together();
        $agent_city = $Together->ColonyCity(1);
        if (!empty($agent_city)) {
            $where['cityRegionId'] = ['in', $agent_city];
        }

        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];

        //查询所代理的景区
        $colony = Db::name("community_colony")->field("id,name")->where($where)->select();
        $enable_status = Db::name("config_attribute")->where(['key' => "enable_status"])->value("value");
        $enable_status = explode("|", $enable_status);
        foreach ($enable_status as $k => $v) {
            $enable_status[$k + 1] = $v;
        }
        unset($enable_status[0]);
        $this->assign("enable_status", $enable_status);
        //查询详细信息
        if (!empty($_GET['id'])) {
            $detail = Db::name("community_colony_manager")->where(['id' => $_GET['id']])->find();
            //查询粉丝信息
            $detail['realName'] = Db::name("admin_fans")->where(['id' => $detail['fans_id']])->value("realName");
            //关联景区
            foreach ($colony as $k => $v) {
                $black = Db::name("community_colony_manager_colony")->where(['colony_id' => $v['id'], 'manager_id' => $_GET['id']])->value("*");
                $colony[$k]['select'] = empty($black) ? 0 : 1;
            }
            $this->assign("detail", $detail);
            $this->assign("colony", $colony);
            return $this->fetch('editManager');
        } else {
            $this->assign("colony", $colony);
            return $this->fetch('addManager');
        }
    }

    //保存景区管理员信息
    public function saveManager()
    {
        //开启事物
        Db::startTrans();
        try {
            $common = new Common();
            if (empty($_POST['id'])) {
                $rule = [
                    ["user_id", "require", "请选择关联用户"],
                    //["colony", "require", "请选择关联小区"],
                    ["name", "require", "请输入账号"],
                    ["password", "require", "请输入密码"],
                ];
            } else {
                $rule = [
                    ["user_id", "require", "请选择关联用户"],
                    //["community_id", "require", "请选择关联小区"],
                ];
            }
            $validate = new Validate($rule);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                throw new Exception($validate->getError());
            }
            if ($data['password'] != $data['password1']) {
                throw new Exception("两次输入的密码不一致");
            }
            if (!empty($data['password'])) {
                $len = strlen($data['password']);
                if ($len < 6) {
                    throw new Exception("密码必须大于6位字符");
                }
                $managerDate['password'] = md5($data['password']);
            }
            if (!empty($data['id'])) {
                $accountWhere['table'] = "community_colony_manager";
                $accountWhere['table_id'] = ['neq', $data['id']];
            } else {
                $accountWhere['name'] = $_POST['name'];
                //判断账号是否已存在
                $isname = Db::name("admin_account_data")->where($accountWhere)->value("id");
                if (!empty($isname)) {
                    throw new Exception("该账号已存在，请勿重复注册");
                }
                $managerDate['name'] = $data['name'];
            }
            $thisWechat = Session::get("thisWechat");
            $managerDate['fans_id'] = $data['user_id'];
            $managerDate['status'] = $data['status'];
            $managerDate['uniacid'] = $thisWechat['id'];

            //2021年1月5日12:17:26 待做
            if(!empty($data['role'])){
                $managerDate['role'] = $data['role'];
            }

            if (empty($data['id'])) {
                $managerDate['addtime'] = time();
                $managerDate['add_id'] = Session::get("id");
                //添加管理员账号
                $managerid = Db::name("community_colony_manager")->insertGetId($managerDate);
                //关联景区
                $colony = '';
                $colonyName = '';
                if (!empty($_POST['colony'])) {
                    $colony = $_POST['colony'];
                    $addData['manager_id'] = $managerid;
                    $addData['addtime'] = time();
                    $addData['add_id'] = Session::get("id");
                    foreach ($colony as $k => $v) {
                        $addData['colony_id'] = $v;
                        $communityData['community_id'] = $v;
                        //查询景区name
                        $name = Db::name("community_colony")->where(['id' => $v])->value("name");
                        $colonyName .= $name . ",";
                        Db::name("community_colony_manager_colony")->insert($addData);
                    }
                }
                //记录日志
                $log['remark'] = "【" . Session::get("user_name") . "】添加景区管理员【" . $data['name'] . "】,关联景区【" . $colonyName . "】";
                $log['controller'] = "District";
                $log['methods'] = "saveManager";
                $common->addLog($log);
                //记录账号信息
                $AccountData['name'] = $managerDate['name'];
                $AccountData['password'] = $managerDate['password'];
                $AccountData['addtime'] = time();
                $AccountData['add_id'] = Session::get("id");
                $AccountData['table'] = "community_colony_manager";
                $AccountData['table_id'] = $managerid;
                $common->addAccountData($AccountData);
            } else {
                $managerDate['updatetime'] = time();
                $managerDate['update_id'] = Session::get("id");
                //添加管理员账号
                Db::name("community_colony_manager")->where(['id' => $data['id']])->update($managerDate);
                $managerid = $data['id'];
                //关联景区
                $colony = '';
                $colonyName = '';
                if (!empty($_POST['colony'])) {
                    //查询已绑定的景区
                    $oldcity = Db::name("community_colony_manager_colony")->where(['manager_id' => $managerid])->field("id,colony_id")->select();
                    $oldcity = array_column($oldcity, "colony_id");
                    $colony = $_POST['colony'];
                    $addData['manager_id'] = $managerid;
                    $addData['addtime'] = time();
                    $addData['add_id'] = Session::get("id");
                    //不包含执行删除
                    foreach ($oldcity as $k => $v) {
                        if (!in_array($v, $colony)) {
                            Db::name("community_colony_manager_colony")->where(['colony_id' => $v, 'manager_id' => $managerid])->delete();
                        }
                    }
                    foreach ($colony as $k => $v) {
                        $addData['colony_id'] = $v;
                        $communityData['community_id'] = $v;
                        //查询景区name
                        $name = Db::name("community_colony")->where(['id' => $v])->value("name");
                        $colonyName .= $name . ",";
                        if (in_array($v, $oldcity)) {
                            continue;
                        }
                        Db::name("community_colony_manager_colony")->insert($addData);
                    }
                } else {
                    Db::name("community_colony_manager_colony")->where(['manager_id' => $managerid])->delete();
                }
                //获取管理员信息
                $name = Db::name("community_colony_manager")->where(['id' => $data['id']])->value("name");
                //记录日志
                $log['remark'] = "【" . Session::get("user_name") . "】修改景区管理员【" . $name . "】信息,关联景区【" . $colonyName . "】";
                $log['controller'] = "District";
                $log['methods'] = "saveManager";
                $common->addLog($log);
                //记录账号信息
                if (!empty($managerDate['name'])) {
                    $AccountData['name'] = $managerDate['name'];
                }
                if (!empty($managerDate['password'])) {
                    $AccountData['password'] = $managerDate['password'];
                }
                $AccountData['addtime'] = time();
                $AccountData['add_id'] = Session::get("id");
                $AccountData['table'] = "community_colony_manager";
                $AccountData['table_id'] = $managerid;
                $common->updateAccountData($AccountData, "community_colony_manager", $data['id']);
            }
            Db::commit();
            $black['code'] = 0;
            $black['msg'] = "添加成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //删除景区管理员
    public function delManager()
    {
        Db::startTrans();
        try {
            $id = $_POST['id'];
            $name = Db::name("community_colony_manager")->where(['id' => ['in', $id]])->field("name")->select();
            $res = Db::name("community_colony_manager")->where(['id' => ['in', $id]])->delete();  //删除账号
            //账号库删除
            $dataWhere['table'] = "community_colony_manager";
            $dataWhere['table_id'] = ['in', $id];
            Db::name("system_account_data")->where($dataWhere)->delete();
            Db::name("community_colony_manager_colony")->where(['manager_id' => ['in', $id]])->delete(); //删除关联的小区权限
            if (empty($res)) {
                throw new Exception("删除失败");
            }
            $common = new Common();
            foreach ($name as $k => $v) {
                $log['remark'] = "【" . Session::get("user_name") . "】删除景区管理员,景区管理员账号【" . $v['name'] . "】";
                $log['controller'] = "District";
                $log['methods'] = "delManager";
                $common->addLog($log);
            }
            Db::commit();
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }


}